<template>
  <div class="box">
    <h3>发布</h3>
    <van-cell-group style="background:none">

      <!-- 标题 -->
      <van-field v-model="bt" placeholder="请输入标题" style="margin-bottom: 10px;" />

      <!-- 发布的地方 -->
      <van-field readonly clickable name="picker" :value="cate_name" style="margin-bottom: 10px;" placeholder="选择标题"
        @click="showPicker = true" />

      <van-popup v-model="showPicker" position="bottom">
        <van-picker value-key="name" show-toolbar :columns="columns" @confirm="onConfirm"
          @cancel="showPicker = false" />
      </van-popup>

      <!-- 发布内容 -->
      <van-field v-model="message" rows="2" autosize style="margin-bottom: 10px" type="textarea" placeholder="请输入内容"
        show-word-limit />

      <!-- 上传图片 -->
      <van-field name="uploader" style="margin-top: 10px;background:none">
        <template #input>
          <van-uploader v-model="uploader" multiple :max-count="3" />
        </template>
      </van-field>

    </van-cell-group>
    <van-button type="primary" color="#3399ff" @click="publish" size="large" style="width: 75%" class="button">确定
    </van-button>
  </div>
</template>

<script>
import { Uploader, Picker, Popup, Toast } from 'vant';
import { mapState } from 'vuex';
import { getQiniuToken, uploadQiniu } from '../api/api'

export default {
  components: {
    [Uploader.name]: Uploader,
    [Picker.name]: Picker,
    [Popup.name]: Popup,
  },
  data() {
    return {
      message: '',
      bt: '',
      cate_id: '',
      cate_name: '',
      columns: [],
      showPicker: false,
      uploader: [],
    }
  },
  // 请求分类
  created() {
    // 请求 分类
    this.$http
      .post("/api/get_cate_list")
      .then((res) => {
        this.columns = res.data.data;
        this.cate_id = res.data.data._id
      })
  },
  // vuex引用简单方法
  computed: {
    ...mapState(['uid', 'userInfo'])
  },

  methods: {
    // ..............................
    // 上传图片
    async upload(uploader) {
      // 接受upload  [file]组成的数组
      if (!Array.isArray(uploader) || uploader.length === 0) {
        return [];
      }

      let task = uploader.map((v) => {
        return new Promise((resolve) => {
          let file = v.file;
          // 生成一个随机名字
          let { type } = file;
          type = type.split('/')[1];

          // 重新命名
          let file_name = `${new Date().getTime()}_${Math.random()
            .toString(36)
            .slice(2)}.${type}`;

          getQiniuToken().then(res => {

            const formdata = new FormData();
            formdata.append("file", file);
            formdata.append("token", res.data.token);
            formdata.append("key", file_name);

            // 上传到七牛云的服务器了
            uploadQiniu(formdata).then(res => {
              resolve(`http://toutiao.longxiaokj.com/` + res.data.key);
            });
          });
        });
      });

      let imageSrc = await Promise.all(task);
      return imageSrc
      // 上传多图
      // @return  上传到服务器的图片路径
    },
    // 调接口
    async publish() {
      // 判断是否登录
      let uid = this.uid
      if (uid) {
        // 登陆时 可以执行

        let imageSrc = await this.upload(this.uploader);
        this.uploader = imageSrc;
        // 发布
        this.$http.post('/api/add_article', {
          title: this.bt,
          content: this.message,
          cate_name: this.cate_name,
          cate_id: this.cate_id,
          author: this.userInfo.nickname,
          author_id: this.userInfo._id,
          imageSrc: this.uploader
        }).then((res) => {
          if (res.data.code == 0) {
            this.$toast('恭喜您发布成功');

            //成功时数据清空 
            this.bt = '';         //标题
            this.cate_name = '';   //发布栏
            this.message = '';    //发布内容
            this.uploader = []   //发布图片
          }
        });
        // 若没登录
      } else {
        Toast('请您先登录~');
        setTimeout(() => {
          this.$router.push('login')
        }, 2000);
      }



    },

    onConfirm({ name, _id }) {
      this.cate_name = name;
      this.cate_id = _id;
      this.showPicker = false;
    },
  },
};
</script>

<style scoped lang="less">
* {
  text-align: center;
}

.aaa {
  float: left;
}

.button {
  margin-top: 80px;
}

.box {
  width: 100%;
  height: 55px;
  // background-color: #3399ff;
  background: url(../../public/img/banners.png) center;
  background-size: 100%;
  // height: 101vh;
  //  background-image: url(../../public/img/bj5.jpg);
}

.box h3 {
  color: white;
  line-height: 55px;
  margin-top: 0;
  margin-bottom: 0;
}
</style>